package com.ouc.eddyAlgorithm.utils;

import com.ouc.common.constant.VariableName;
import com.ouc.common.entity.NcData;
import com.ouc.common.ncRead.NcDao;
import com.ouc.common.ncRead.impl.NcDaoImpl;
import com.ouc.common.utils.MathUtils;
import com.ouc.common.utils.ProgramUtil;
import com.ouc.common.utils.SystemUtils;
import com.ouc.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import ucar.nc2.NetcdfFile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * 调用python的Pet方法
 * 写成一个bat文件然后调用这个bat文件
 *
 * @author B504
 */
@Slf4j
public class PythonPetUtil {
  public static String getPetPython(String pythonFilePath, String ncFilePath,
                                    Integer startLon, Integer endLon, Integer startLat, Integer endLat) throws IOException {
    try {
      String parentPath = new File(pythonFilePath).getParentFile().getCanonicalPath();
      File batFile = new File(parentPath + File.separator + "command.bat");
      BufferedWriter bw = new BufferedWriter(new FileWriter(batFile));
      StringBuilder sb = new StringBuilder();
      //  各种参数
      sb.append("call activate binder-pyeddytracker>> d:\\acousticData\\dblog.txt 2>&1").append("\r\n")
          .append("python").append(" ").append(pythonFilePath).append(" ")
          .append("--aa").append(" ").append(ncFilePath).append(" ")
          .append("--bb").append(" ").append(startLon).append(" ")
          .append("--cc").append(" ").append(endLon).append(" ")
          .append("--dd").append(" ").append(startLat).append(" ")
          .append("--ee").append(" ").append(endLat);
      bw.write(sb.toString());
      // 因为cmd窗口原因不会等到完全生成.bat文件，所以不能在这里写需要在函数外面写
//      ProgramUtil.startProgram(batFile.getCanonicalPath());
      bw.close();
      return batFile.getCanonicalPath();
    } catch (Exception e) {
      return null;
    }


  }

  /**
   * 运行python程序不生成bat文件
   * <p>
   * python的环境变量所在python绝对路径
   *
   * @param pythonFilePath python文件绝对路径
   * @param ncFilePath     nc文件绝对路径
   * @param startLon       开始经度
   * @param endLon         结束经度
   * @param startLat       开始纬度
   * @param endLat         结束纬度
   * @return
   */
  public static Boolean startDeepLearning(String pythonFilePath, String ncFilePath,
                                          Integer startLon, Integer endLon, Integer startLat, Integer endLat) {
    try {
      NcDao ncDao = new NcDaoImpl();
      NetcdfFile ncFile = NetcdfFile.open(ncFilePath);
      Map<String, NcData> ncDataMap = ncDao.getNcDataOfOneDimensional(ncFile);
      float[] lon = ncDataMap.get(ncDao.getVariable(ncFile, VariableName.LON).getShortName()).getData1D();
      float[] lat = ncDataMap.get(ncDao.getVariable(ncFile, VariableName.LAT).getShortName()).getData1D();
      startLon = (int) Math.ceil(MathUtils.middle(lon[0], startLon, lon[lon.length - 1]));
      endLon = (int) Math.floor(MathUtils.middle(lon[0], endLon, lon[lon.length - 1]));
      startLat = (int) Math.ceil(MathUtils.middle(lat[0], startLat, lat[lat.length - 1]));
      endLat = (int) Math.floor(MathUtils.middle(lat[0], endLat, lat[lat.length - 1]));
      //  各种参数
      String header = "cmd /c ";
      ncFilePath = " --aa " + ncFilePath;
      String startLonOfString = " --bb " + startLon;
      String endLonOfString = " --cc " + endLon;
      String startLatOfString = " --dd " + startLat;
      String endLatOfString = " --ee " + endLat;
      String argsParm = ncFilePath + startLonOfString + endLonOfString + startLatOfString + endLatOfString;
      String sb = header + pythonFilePath.charAt(0) + ":" + " & " +
          "cd " + new File(pythonFilePath).getParent() + " & " +
          "call activate pytorch-cpu" + " & " +
          "python " + pythonFilePath +
          argsParm;
      Process pro = Runtime.getRuntime().exec(sb);
      ProgramUtil.errorMessage(pro);
      ProgramUtil.infoMessage(pro);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

  }


  public static Boolean startPythonOfPet(String pythonFilePath, String ncFilePath,
                                         Integer startLon, Integer endLon, Integer startLat, Integer endLat) {
    try {
      NcDao ncDao = new NcDaoImpl();
      NetcdfFile ncFile = NetcdfFile.open(ncFilePath);
      Map<String, NcData> ncDataMap = ncDao.getNcDataOfOneDimensional(ncFile);
      float[] lon = ncDataMap.get(ncDao.getVariable(ncFile, VariableName.LON).getShortName()).getData1D();
      float[] lat = ncDataMap.get(ncDao.getVariable(ncFile, VariableName.LAT).getShortName()).getData1D();
//      startLon = (int) Math.ceil(MathUtils.middle(lon[0], startLon, lon[lon.length - 1]));
//      endLon = (int) Math.floor(MathUtils.middle(lon[0], endLon, lon[lon.length - 1]));
//      startLat = (int) Math.ceil(MathUtils.middle(lat[0], startLat, lat[lat.length - 1]));
//      endLat = (int) Math.floor(MathUtils.middle(lat[0], endLat, lat[lat.length - 1]));
      if (SystemUtils.isWindows()) {
        //  各种参数
        String header = "cmd /c ";
        String ncFilePathParm = " --aa " + ncFilePath;
        String startLonOfString = " --bb " + startLon;
        String endLonOfString = " --cc " + endLon;
        String startLatOfString = " --dd " + startLat;
        String endLatOfString = " --ee " + endLat;
        String destPath = " --ff " + new File(ncFilePath).getParent();
        String argsParm = ncFilePathParm + startLonOfString + endLonOfString + startLatOfString + endLatOfString + destPath;
        String sb = header + pythonFilePath.charAt(0) + ":" + " & " +
            "cd " + new File(pythonFilePath).getParent() + " & " + "python " +
            FileUtils.getName(pythonFilePath) + argsParm;
        Process pro = Runtime.getRuntime().exec(sb);
        ProgramUtil.errorMessage(pro);
        ProgramUtil.infoMessage(pro);
      } else if (SystemUtils.isLinux()) {
        log.info("your pythonPath is:" + pythonFilePath);
        //cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonPath).getParent() + " && python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc \"POLYGON\\(\\(105@145,0@145,0@50,105@50,105@145\\)\\)\" --dd " + outPath};
        //cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonPath).getParent() + " && python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc \"" + polygon.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)") + "\" --dd " + outPath};
        // cmd = new String[]{"gnome-terminal", "--working-directory=" + new File(pythonPath).getParent(), "-e", "/bin/bash -c 'python3 " + pythonPath + " --aa " + startTime + " --bb " + endTime + " --cc "" + polygon.replaceAll("\(", "\\(").replaceAll("\)", "\\)") + "" --dd " + outPath + "; exec /bin/bash -i'"};
        String[] cmd = new String[]{"/bin/bash", "-c", "cd " + new File(pythonFilePath).getParent() + " && python3 " + pythonFilePath + " --aa " + ncFilePath + " --bb " + startLon + " --cc " + endLon + " --dd " + startLat + " --ee " + endLat + " --ff " + new File(ncFilePath).getParent()};
        log.info("your cmd Arrays is" + Arrays.toString(cmd));

        StringBuilder sb = new StringBuilder();
        for (String s1 : cmd) {
          sb.append(s1);
        }
        log.info("stringbuilder is" + sb.toString());
        log.info("your cmd python path is:" + new File(pythonFilePath));
        Process pro = Runtime.getRuntime().exec(cmd);
        ProgramUtil.errorMessage(pro);
        ProgramUtil.infoMessage(pro);
      }

      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}
